import 'dart:async';
import 'dart:convert';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import '../../../utils/eventBus/eventBus.dart';
import '../../../utils/sputils/SpUtils.dart';
import '../../../utils/string/StringConstant.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../entities/UserEntity.dart';

part 'user_event.dart';
part 'user_state.dart';

/**
 * 取
 * var userEntity = BlocProvider.of<UserBloc>(context).state.userEntity;
 *
 * 更新
 * BlocProvider.of<UserBloc>(context).add(UpdateUserEvent(userState: UserState(userEntity: p0.data)));
 *
 *
 * builder
 *
    BlocBuilder<UserBloc,UserState>(
    builder: (context, state) {
    return Container();
    },
    )
 */

class UserBloc extends Bloc<UserEvent, UserState> {
  UserBloc() : super(UserState(userEntity: UserBlocTool.getUser())) {
    on<UserEvent>((event, emit) async {
      if (event is UpdateUserEvent) {
        //更新
        assert(event.userState.userEntity != null,
            "UserBloc UpdateUserEvent更新事件，UserEntity一定要有值");

        bool isLogin = false;
        if (UserBlocTool.userEntity == null) {
          isLogin = true;
        }
        UserEntity? userEntity = event.userState.userEntity;
        UserBlocTool.userEntity = userEntity;
        SpUtils.saveData(SpUtils.userInfo, jsonEncode(userEntity?.toJson()))
            .then((value) {
          if (isLogin) {
            // 登录成功
            print('UserBloc-------发送登录成功的通知---------');

            bus.emit(StringConstant.UserLoginInEvent);
          } else {
            //更新用户信息
            bus.emit(StringConstant.UserInfoUpdateEvent, false);
          }
        });
        emit(UserState(userEntity: userEntity));
      } else if (event is UnLoginUserEvent) {
        //退出登录
        await UserBlocTool.removeAuth();
        UserBlocTool.userEntity = null;
        SpUtils.remove(SpUtils.userInfo).then((value) {
          //退出登录bus
          bus.emit(StringConstant.UserLoginOutEvent, false);
        });
        emit(UserState(userEntity: null));
      }
    });
  }
}

/**
 * UserBloc操作集中管理
 */
class UserBlocTool {
  //缓存当前用户信息
  static UserEntity? userEntity = null;

  //缓存当前用户凭证
  static String? userAuth;

  //更新 userEntity
  static update(BuildContext context, UserEntity userEntity) {
    BlocProvider.of<UserBloc>(context)
        .add(UpdateUserEvent(userState: UserState(userEntity: userEntity)));
  }

  //退出登录操作
  static loginOut(BuildContext context) async {
    BlocProvider.of<UserBloc>(context)
        .add(UnLoginUserEvent(userState: UserState(userEntity: null)));
  }

  //保存用户凭证
  static Future saveAuth(String auth) {
    userAuth = auth;
    return SpUtils.saveData(StringConstant.UserAuth, auth);
  }

  //删除用户凭证
  static Future removeAuth() {
    userAuth = null;
    return SpUtils.remove(StringConstant.UserAuth);
  }

  //获取用户凭证
  static Future<String?> getUserAuth() async {
    if (!SilTools.stringIsEmpty(userAuth)) {
      return userAuth;
    }

    String? auth = await SpUtils.getData(StringConstant.UserAuth);
    if (!SilTools.stringIsEmpty(auth)) {
      userAuth = auth;
    }

    return auth;
  }

  ///返回当前用户对象
  static UserEntity? getUser() {
    if (userEntity != null) {
      return userEntity;
    }

    try {
      String? json = SpUtils.getData(SpUtils.userInfo);
      if (!SilTools.stringIsEmpty(json)) {
        UserEntity user = UserEntity.fromJson(jsonDecode(json!));
        userEntity = user;
        return user;
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  ///是否登录
  static bool isLogin() {
    UserEntity? entity = getUser();
    if (entity != null) {
      return !SilTools.stringIsEmpty(entity.id);
    }
    return false;
  }

  ///返回当前用户对象uid
  static String uid() {
    UserEntity? userEntity = getUser();

    if (userEntity != null) {
      if (!SilTools.stringIsEmpty(userEntity.id)) {
        return userEntity.id!;
      }
    }

    return "";
  }
}
